package cron

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"
)

type RepeatRuleSchedule struct {
	delayArr []int
	idx      int
}

func RepeatRule(str string) (*RepeatRuleSchedule, error) {
	if strings.TrimSpace(str) == "" {
		return nil, errors.New("expression is empty")
	}
	arr := strings.Fields(str)
	delayArr := make([]int, len(arr))
	for idx, val := range arr {
		if v, err := strconv.Atoi(val); err != nil {
			return nil, fmt.Errorf("expression parse err %s", val)
		} else {
			delayArr[idx] = v
		}
	}
	return &RepeatRuleSchedule{
		delayArr: delayArr,
		idx:      0,
	}, nil
}

func (schedule *RepeatRuleSchedule) Next(t time.Time) time.Time {
	idx := schedule.idx
	if idx < len(schedule.delayArr) {
		delay := schedule.delayArr[idx]
		schedule.idx = idx + 1
		return t.Add(time.Second * time.Duration(delay))
	} else {
		return time.Time{}
	}
	// return t.Add(schedule.Delay - time.Duration(t.Nanosecond())*time.Nanosecond)
}

func (schedule *RepeatRuleSchedule) DependOnCb() bool {
	return true
}
